//
//  KRegisterViewController.m
//  Keping
//
//  Created by 柯平 on 2017/6/22.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KRegisterViewController.h"
#import "KTextCell.h"
#import "KVeritifyCodeCell.h"
#import "KAgreementViewController.h"
#import "KUserData.h"
#import "KLoginRequest.h"
#import "KCodeRequest.h"
#import "KRequestData.h"
#import "KRegisterPhoneModel.h"
#import "KRegistrationPhoneCell.h"
#import "KRegistrationPhoneView.h"
#import "AppDelegate.h"
#import <XXNibBridge/XXNibBridge.h>


@interface KRegisterViewController ()<UIGestureRecognizerDelegate>
{
    NSArray* items;
    
}
@property(nonatomic,strong)UILabel* registerLabel;
@property(nonatomic,strong)UIButton* registerBtn;
@property(nonatomic,strong)UIButton* agreeBtn;
@property(nonatomic,strong)YYLabel* textLabel;
@property(nonatomic,assign)CGFloat tableTop;

@property(nonatomic,copy)NSString* phone;
@property(nonatomic,copy)NSString* areaCode;
@property(nonatomic,copy)NSString* email;
@property(nonatomic,copy)NSString* nickName;
@property(nonatomic,copy)NSString* passWord;
@property(nonatomic,copy)NSString* confirmPwd;
@property(nonatomic,copy)NSString* smsCode;

@property(nonatomic,copy)NSArray* phoneCode;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) KRegistrationPhoneView *phoneView;

@end

@implementation KRegisterViewController

-(void)viewWillAppear:(BOOL)animated
{    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    self.whiteNaviBar.hidden = NO;
    [self.view bringSubviewToFront:self.whiteNaviBar];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getData];
    items = @[@"Username",@"Email",@"Phone",@"Enter Verification Code",@"Password",@"Confirm Password"];
    
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    self.tableView.rowHeight = 54;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableTop = self.registerLabel.bottom;
    [self.tableView registerNib:[UINib nibWithNibName:[KRegistrationPhoneCell className] bundle:nil] forCellReuseIdentifier:[KRegistrationPhoneCell className]];
    [self layout];
}

- (void)getData {
    [super getData];
    [self showLoading];
    WEAKSELF
    KRegisterPhoneRequest *request = [[KRegisterPhoneRequest alloc] init];
    request.params = @{@"key":@"phoneCode"};
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            NSMutableArray *array = [NSMutableArray new];
            NSArray *arr = [dict objectForKey:@"glConfigViews"];
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *tmp = [arr objectAtIndex:i];
                KRegisterPhoneModel *model = [KRegisterPhoneModel modelWithDictionary:tmp];
                [array addObject:model];
            }
            weakSelf.phoneCode = [array copy];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

#pragma mark - Network
-(void)requestCode{
    if (!StringNotEmpty(self.areaCode)) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Please select Area Code!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    KCodeRequest* codeRequest = [[KCodeRequest alloc] initWithPhone:self.phone];
    codeRequest.params = @{@"phone":self.phone,@"prix":self.areaCode};
    [codeRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        KRequestData* data = [KRequestData modelWithJSON:request.responseData];
        if (data.statusCode == 200) {
            [self showSuccess:data.msg];
        }else{
            [self showErrorText:data.msg errCode:data.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self showError:request.error];
    }];
}

-(void)registerAction{
    if (![self.nickName isNotBlank]) {
        [self showErrorText:@"The user name cannot be empty."];
        return;
    }
    if (![self.email isNotBlank]) {
        [self showErrorText:@"EMail cannot be empty."];
        return;
    }
    if (![self.phone isNotBlank]) {
        [self showErrorText:@"The phone number can't be empty."];
        return;
    }
    if (![self.smsCode isNotBlank]) {
        [self showErrorText:@"Verify that the code cannot be empty."];
        return;
    }
    
    if (![self.passWord isNotBlank]) {
        [self showErrorText:@"The password cannot be empty."];
        return;
    }
    if (![self.confirmPwd isNotBlank]) {
        [self showErrorText:@"Verify that the password cannot be empty."];
        return;
    }
    if (![self.passWord isEqualToString:self.confirmPwd]) {
        [self showErrorText:@"The two passwords do not match!"];
        return;
    }
    
    [self showLoading:@"Registering..."];
    KRegisterRequest* request = [[KRegisterRequest alloc] init];
    request.params = [NSDictionary dictionaryWithObjectsAndKeys:self.phone,@"phone",self.email,@"email",self.nickName,@"nickName",self.smsCode,@"smsCode",[self.passWord md5String],@"passWord",[self.confirmPwd md5String],@"confirmPwd", nil];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        KUserData* data = [KUserData modelWithJSON:request.responseData];
        if (data.statusCode == 200) {
            [self showSuccess:@"Register successfully!"];
            if ([data archiveWithKey:@"KTempUserData"]) {
                
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self showErrorText:data.msg errCode:data.statusCode];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [self showErrorText:@"Registration failed!"];
    }];
    
}

-(void)layout{
    [self.tableView setFrame:CGRectMake(20, self.tableTop, kScreenWidth-40, items.count*55)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.registerBtn setFrame:CGRectMake(10, self.tableView.bottom+20, kScreenWidth-20, 39)];
    [self.agreeBtn setFrame:CGRectMake(self.registerBtn.left, self.registerBtn.bottom+5, 20, 20)];
    [self.textLabel setFrame:CGRectMake(self.agreeBtn.right+10, self.agreeBtn.top, kScreenWidth-self.agreeBtn.width-20, 20)];
}

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        [_bgView setFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddePhoneView)];
        gesture.delegate = self;
        [_bgView addGestureRecognizer:gesture];
        _bgView.backgroundColor = [UIColor clearColor];
    }
    return _bgView;
}

- (void)hiddePhoneView {
    [_bgView removeFromSuperview];
}

- (KRegistrationPhoneView *)phoneView {
    if (!_phoneView) {
        WEAKSELF
        _phoneView = [KRegistrationPhoneView xx_instantiateFromNib];
        [_phoneView setFrame:CGRectMake(20, 254, 110, 120)];
        _phoneView.selectPhoneCode = ^(KRegisterPhoneModel *model) {
            [weakSelf hiddePhoneView];
            weakSelf.areaCode = model.content;
            [weakSelf.tableView reloadRow:2 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        };
    }
    return _phoneView;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // 点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    // 点击了tableViewCell，view的类名为UITableViewCellContentView，则不接收Touch点击事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return items.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    NSString* placeholder = items[indexPath.row];
    if ([placeholder isEqualToString:@"Enter Verification Code"]) {
        KVeritifyCodeCell* cell = [tableView dequeueReusableCellWithIdentifier:[KVeritifyCodeCell className]];
        if (!cell) {
            cell = [[KVeritifyCodeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KVeritifyCodeCell className]];
        }
        cell.textTf.placeholder = items[indexPath.row];
        [cell.codeBtn setTitle:@"Get Veritification Code" forState:UIControlStateNormal];
        cell.codeBtn.layer.cornerRadius = 4.0;
        cell.buttonBlock = ^{
            if (![weak_self.phone isNotBlank]) {
                [weak_self showErrorText:@"Mobile phone number can not be empty!"];
                return;
            }else{
                [weak_self requestCode];
            }
        };
        cell.codeBlock = ^(NSString *text) {
            if ([text isNotBlank]) {
                weak_self.smsCode = text;
            }
        };
        return cell;
    } else if ([placeholder isEqualToString:@"Phone"]) {
        KRegistrationPhoneCell *cell = [tableView dequeueReusableCellWithIdentifier:[KRegistrationPhoneCell className]];
        cell.textTf.placeholder = items[indexPath.row];
        if (self.areaCode) {
            [cell.textBtn setTitle:self.areaCode forState:UIControlStateNormal];
        }
        
        cell.buttonBlock = ^{
            [weak_self.view endEditing:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [weak_self.bgView addSubview:weak_self.phoneView];
                weak_self.phoneView.titleArr = weak_self.phoneCode;
                [app.window addSubview:weak_self.bgView];
            });
        };
        cell.codeBlock = ^(NSString *text) {
            if ([text isNotBlank]) {
                weak_self.phone = text;
            }
        };
        return cell;
    } else {
        KTextCell* cell = [tableView dequeueReusableCellWithIdentifier:[KTextCell className]];
        if (!cell) {
            cell = [[KTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KTextCell className]];
        }
        cell.textTf.placeholder = items[indexPath.row];
        cell.textTf.secureTextEntry = NO;
        if ([items[indexPath.row] isEqualToString:@"Password"] || [items[indexPath.row] isEqualToString:@"Confirm Password"]) {
            cell.textTf.secureTextEntry = YES;
        }
        cell.textBlock = ^(NSString *text) {
            if ([@"Username" isEqualToString:placeholder]) {
                weak_self.nickName = text;
            }else if ([@"Email" isEqualToString:placeholder]){
                weak_self.email = text;
            }else if ([@"Phone" isEqualToString:placeholder]){
                weak_self.phone = text;
            }else if ([@"Password" isEqualToString:placeholder]){
                weak_self.passWord = text;
            }else if ([@"Confirm Password" isEqualToString:placeholder]){
                weak_self.confirmPwd = text;
            }
        };
        return cell;
    }
    return nil;
}



-(UIButton *)agreeBtn
{
    if (!_agreeBtn) {
        _agreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_agreeBtn setImage:[UIImage imageNamed:@"agree"] forState:UIControlStateNormal];
        [_agreeBtn setImage:[UIImage imageNamed:@"disagree"] forState:UIControlStateSelected];
        @weakify(self);
        [_agreeBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            weak_self.agreeBtn.selected = !weak_self.agreeBtn.selected;
        }];
        [self.view addSubview:_agreeBtn];
    }
    return _agreeBtn;
}

-(YYLabel *)textLabel
{
    if (!_textLabel) {
        _textLabel = [[YYLabel alloc]init];
        _textLabel.textAlignment = NSTextAlignmentLeft;
        _textLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
        __weak typeof(self) weak_self = self;
        NSMutableAttributedString* tt = [[NSMutableAttributedString alloc]initWithString:@"I agree the terms of the User Agreement"];
        tt.font = [UIFont systemFontOfSize:14];
        tt.alignment = NSTextAlignmentCenter;
        [tt addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:tt.rangeOfAll];
        [tt setTextHighlightRange:NSMakeRange(0, 25) color:[UIColor darkGrayColor] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            weak_self.agreeBtn.selected = !weak_self.agreeBtn.selected;
        }];
        [tt setTextHighlightRange:NSMakeRange(25, tt.length-25) color:[UIColor colorWithHexString:@"714FFA"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            KAgreementViewController* vc = [KAgreementViewController new];
            vc.title = @"User Agreement";
            [weak_self.navigationController pushViewController:vc animated:YES];
        }];
        tt.alignment = NSTextAlignmentLeft;
        _textLabel.attributedText = tt;
        [self.view addSubview:_textLabel];
    }
    return _textLabel;
}

-(UILabel *)registerLabel
{
    if (!_registerLabel) {
        _registerLabel = [UILabel new];
        _registerLabel = [[UILabel alloc]init];
        _registerLabel.text = @"Register";
        [_registerLabel sizeToFit];
        _registerLabel.textAlignment = NSTextAlignmentCenter;
        _registerLabel.textColor = [UIColor colorWithHexString:@"714FFA"];
        _registerLabel.font = [UIFont boldSystemFontOfSize:32];
        [_registerLabel setFrame:CGRectMake(0, 74, kScreenWidth, 54)];
        [self.view addSubview:_registerLabel];
    }
    return _registerLabel;
}

-(UIButton *)registerBtn
{
    if (!_registerBtn) {
        _registerBtn = [UIButton commonButtonWithTitle:@"Register"];
        _registerBtn.layer.cornerRadius = 19.5;
        [_registerBtn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_registerBtn];
    }
    return _registerBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
